package com.vcredit.creditcat.interceptor;

import java.io.IOException;
import java.lang.reflect.Type;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JavaType;
import com.vcredit.creditcat.vo.JsonResult;

@Component
public class JsonMessageConverter extends MappingJackson2HttpMessageConverter {
	@Override
	public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException {

		JavaType javaType = getJavaType(type, contextClass);
		return this.getObjectMapper().readValue(inputMessage.getBody(), javaType);
	}

	@Override
	protected void writeInternal(Object object, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {

		if (object instanceof JsonResult) {
			super.writeInternal(object, outputMessage);
		} else {
			super.writeInternal(JsonResult.SuccessResponse(object), outputMessage);
		}

	}

}
